package org.linloong.modules.apis.common.service.impl;// UserServiceImpl.java
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linloong.modules.apis.common.dto.UserLoginDTO;
import org.linloong.modules.apis.common.dto.UserRegisterDTO;
import org.linloong.modules.apis.common.entity.Permission;
import org.linloong.modules.apis.common.entity.Role;
import org.linloong.modules.apis.common.entity.User;
import org.linloong.modules.apis.common.mapper.PermissionMapper;
import org.linloong.modules.apis.common.mapper.RoleMapper;
import org.linloong.modules.apis.common.mapper.UserMapper;
import org.linloong.modules.apis.common.mapper.UserRoleMapper;
import org.linloong.modules.apis.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Transactional
    @Override
    public boolean register(UserRegisterDTO userRegisterDTO) {
        // 检查用户名是否已存在
        User existingUser = this.getByUsername(userRegisterDTO.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 创建用户
        User user = new User();
        user.setUsername(userRegisterDTO.getUsername());
        user.setPassword(SaSecureUtil.md5(userRegisterDTO.getPassword()));
        user.setNickname(userRegisterDTO.getNickname());
        user.setEmail(userRegisterDTO.getEmail());
        user.setPhone(userRegisterDTO.getPhone());
        
        return this.save(user);
    }
    
    @Override
    public SaTokenInfo login(UserLoginDTO userLoginDTO) {
        // 查询用户
        User user = this.getByUsername(userLoginDTO.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证密码
        if (!SaSecureUtil.md5(userLoginDTO.getPassword()).equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        if (user.getStatus() == 0) {
            throw new RuntimeException("账户已被禁用");
        }
        
        // 登录并获取token信息
        StpUtil.login(user.getId());
        
        // 设置用户角色权限
        List<Role> roles = this.getUserRoles(user.getId());
        List<String> roleKeys = roles.stream()
                .map(Role::getRoleKey)
                .collect(Collectors.toList());
       //todo 设置角色
        
        // 获取所有权限
        List<String> permissions = roles.stream()
                .flatMap(role -> this.getRolePermissions(role.getId()).stream())
                .map(Permission::getPermissionKey)
                .distinct()
                .collect(Collectors.toList());

        //todo 设置权限
        return StpUtil.getTokenInfo();
    }
    
    @Override
    public void logout() {
        StpUtil.logout();
    }
    
    @Override
    public User getByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.getOne(queryWrapper);
    }
    
    @Override
    public List<Role> getUserRoles(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }
    
    @Override
    public List<Permission> getRolePermissions(Long roleId) {
        return permissionMapper.selectPermissionsByRoleId(roleId);
    }
}
